<?php
/**
 * return search form and return search_search
 * define param $entities['user']['basics'] = $basics, $entities['user']['field'] = $fields;
 * @return unknown_type
 */
function fw_search_form($entities, $entity) {
	global $db;
	//linked: for sort table with keep search fields
	//form: show form search
	//sql: part for query
	$basics = $entities[$entity]['basics'];
	$fields = $entities[$entity]['fields'];
	$table = $entities[$entity]['table'];
	if (!$basics['entity_key']) {
		$basics['entity_key'] = $basics['entity'];
	}

	//clean basic & fields
	$cleanVar = fw_data_cleanup($fields, $basics);
	$fields  = $cleanVar[0];
	$basics  = $cleanVar[1];

	//clean search result
	fw_data_cleanup2($table, $basics);
	//clean fields/basics
	$sql_search = '';
	if ($basics['entity_key'] == '') {
		$basics['entity_key'] = $entity;
	}

	if (!$basics['refresh_action_ajax']) {
		$basics['refresh_action_ajax'] = $entity.'_search_result';
	}

	if (!$_REQUEST['id_panel']) {
		gain_search_default_get($basics);
	}

	if (SEARCH_HISTORY == 1 && !$_REQUEST['search'] && $_REQUEST['clear'] != msg('fw-clear') && !isset($_REQUEST[$basics['entity_key']]['page']) && !$_REQUEST[$basics['entity_key']]['sort_by'] && !$_REQUEST[$basics['entity_key']]['sort_order'] && !$_REQUEST['id_panel']) {
		gain_search_history_get($basics);
	}

	if ($_REQUEST['id_panel']) {
		unset($_REQUEST[$entity]);
	}

	$clean_me = fw_data_cleanup($fields, $basics);
	$fields = $clean_me[0];
	$basics = $clean_me[1];
	//set javascript submit for search all
	//set clean name
	if ($entities[$entity]['search']['search_fields']) {
		$not_default_search = 0;
		//get default search from history
		//unset($_REQUEST['default_search'][$basics['entity_key']]['limit']);
//		$cnt_default = count($_REQUEST['default_search'][$basics['entity_key']]);

		//default by SCRIPT
		if ($_REQUEST['clear'] == msg('fw-default')) {
			foreach ($entities[$entity]['search']['search_fields'] as $k => $v) {
				if ($v['default_search']) {
					--$not_default_search;
				}
			}
		}
		//beem : use?$not_default_search // $cnt_default
		foreach ($entities[$entity]['search']['search_fields'] as $k => $v) {
			//set addon fields for all search
			if ($fields[$k]) {
				//$v += $fields[$k];
				foreach ($fields[$k] as $k2 => $v2) {
					if (!isset($v[$k2])) {
						$v[$k2] = $v2;
					}
				}
			}

			unset($v['show']);
			unset($v['req']);
			unset($v['vhead']);
			//set type of fields [I,S,A,...]
			if (!isset($v['type'])) {
				if ($fields[$k]['type']) {
					$v['type'] = $fields[$k]['type'];
				}
			}

			if ($v['type'] == 'radio') {
				$v['type'] = 'select';
			}

			if ($v['type'] == 'city') {
				unset($v['param2']);
			}

			if ($v['addon_field']) {
				$v['addon_field'] = '';
			}

			if ($v['default']) {
				$v['default'] = '';
			}

			if ($_REQUEST['clear'] == msg('fw-clear')) {
				$v['default_search'] = '';
			}

			if ($_REQUEST['clear'] == msg('fw-default') && $v['default_search'] != '' && !$basics['group_url'] && $basics['permanent_group'] != 1 && count($_REQUEST['default_search'][$basics['entity_key']]) == 0) {
				$v['default'] = $v['default_search'];
				$_REQUEST[$basics['entity_key']][$k] = $v['default_search'];
			}

			//set label for search fields
			if (!isset($v['head'])) {
				if ($fields[$k]['head']) {
					$v['head'] = $fields[$k]['head'];
				}
			}

			//set query by "search_for"
			//set linked
			if (isset($_REQUEST[$basics['entity_key']][$k])) {
				if ($v['type'] == 'checkbox') {
					$_REQUEST[$k] = $_REQUEST[$basics['entity_key']][$k];
				} else {
					$_REQUEST[$k] = rawurldecode($_REQUEST[$basics['entity_key']][$k]);
				}
			}

			if ($basics['group_url'] == 1) {
				//unset limit search
				unset($_REQUEST['default'][$basics['entity_key']]['limit']);
			}

			if ($v['type'] == 'E') {
				$fn = PREFIX . $k;
				if (function_exists($fn)) {
					//set option for search
					$v['default'] = $_REQUEST[$k];
					$v['set_search'] = 1;
					$v['table_search'] = $basics['table'];
					$v['entity_search'] = $basics['entity'];
					$q = $fn($v, 'action');
					if ($q['search_sql']) {
						$r['sql_search'] .= $q['search_sql'];
						$search_text_arr[$v['head'].': '.$q['search_text']] = 1;
					
						//need to set linked
						$r['linked'] .= $q['linked'];
					}
				}
			}
			if (((((!is_array($_REQUEST[$k]) && trim($_REQUEST[$k]) != '') || $_REQUEST[$k]) && !$_REQUEST['post_form']) || $v['default_search'] != '') && $v['skip'] != 1) {
				$p = 0;
				$v['default'] = $_REQUEST[$k];
				if ($v['default'] != '') {
					if ($v['head'] == '') {
						$p = 1;
					} else if ($v['default'] != $v['head'] && $v['default'] != $v['vhead']) {
						$p = 1;
					}
				}
				if ($_REQUEST['default'][$basics['entity_key']][$k]) {
					$v['disabled'] = 1;
				}
				if ($p == 1) {
					if ($_REQUEST['default_search'][$basics['entity_key']][$k] != $v['default']) {
						++$not_default_search;
					} else {
						--$not_default_search;
					}
				}

				if ($v['search_for']) {
					$r['sql_search'] .= ' AND (';
					$cnt = 0;
					foreach ($v['search_for'] as $k3 => $v3) {
						$word_search = array();
						$op = '';
						if (++$cnt > 1) {
							$r['sql_search'] .= ' OR ';
						}
						if ($v['type'] == 'I' || $v['type'] == 'input') {
							$search_text_arr[$v['head'].': '.$v['default']] = 1;
							$r['sql_search'] .= fw_search_input($_REQUEST[$k], array('inf' => $v, 'field' => $v3, 'main_table' => $basics['table']));
						} else if ($v['type'] == 'country') {
							global $countries;
							$r['sql_search'] .= $v3.'="'.$_REQUEST[$k].'"';
							//keep search history
							$search_text_arr[$v['head'].': '.$countries[$_REQUEST[$k]]] = 1;
						}
						//TODO check other type
					}
					$r['sql_search'] .= ')';
				} else {
					$add_linked = 0;
					//check type of fields
					if ($v['type'] == 'name') {
						$fe_name = $_REQUEST[$k];
						if ($fe_name{0} != '*') {
							$_REQUEST[$k] = '*'.$fe_name;
						}
						$k_search = array($k, $k.'_title', $k.'_first', $k.'_middle', $k.'_last', $k.'_suffix');
						$r['sql_search'] .= ' AND (';
						foreach ($k_search as $_i => $_k) {
							if ($_i > 0) {
								$r['sql_search'] .= ' OR ';
							}
							$r['sql_search'] .= fw_search_input($_REQUEST[$k], array('inf' => $v, 'field' => $_k, 'main_table' => $basics['table']));
						}
						$r['sql_search'] .= ')';
						$search_text_arr[$v['head'].': ' . $fe_name] = 1;
					} else if ($v['type'] == 'input' || $v['type'] == 'I') {
						$r['sql_search'] .= ' AND '.fw_search_input($_REQUEST[$k], array('inf' => $v, 'field' => $k, 'main_table' => $basics['table']));
						//keep search history
						$search_text_arr[$v['head'].': '.$v['default']] = 1;
					} else if ($v['type'] == 'filter_by') {
						if ($v['default'] == '*') {
							$r['sql_search'] .= ' AND '.$v['field'].' REGEXP "^[^a-z]"';
						} else {
							$r['sql_search'] .= ' AND '.$v['field'].' LIKE "'.$v['default'].'%"';
						}
						//keep search history
						$search_text_arr[$v['head'].': '.$v['default']] = 1;
					} else if ($v['type'] == 'select' || $v['type'] == 'S' || $v['type'] == 'select_group' || $v['type'] == 'user') {
						if ($v['default'] == 'none') {
							$r['sql_search'] .= ' AND ('.$basics['table'].'.'.$k.'="" OR '.$basics['table'].'.'.$k.' IS NULL)';
							//keep search history
							$search_text_arr[$v['head'].': '.msg('none')] = 1;
						} else if($v['default'] == 'all') {
							$r['sql_search'] .= ' AND ('.$basics['table'].'.'.$k.'!="" AND '.$basics['table'].'.'.$k.' IS NOT NULL)';
							//keep search history
							$search_text_arr[$v['head'].': '.msg('all')] = 1;
						} else {
							if ($v['default'] != '') {
								//keep search history
								if ($v['type'] == 'user') {
									$users_arr = user_list(','.$v['account_type'].',', $v['visibility']);
									$all = array();
									//flat second dimension and display value
									if ($users_arr['label']) {
										foreach ($users_arr['label'] as $kx => $vx) {
											if ($vx) {
												foreach ($vx as $k2 => $v2) {
													$all[$k2] = $v2;
												}
												$all[implode(',', array_keys($vx))] = $kx;
											}
										}
									}
									$search_text_arr[$v['head'].': '.$all[$v['default']]] = 1;
									$r['sql_search'] .= ' AND '.$basics['table'].'.'.$k.' IN ('.$v['default'].')';
								} else if ($v['param2'] == 'N') {
									//$v['default'] = '"' . $v['default'] . '"';
									$search_text_arr[$v['head'].': '.$v['default']] = 1;
									$r['sql_search'] .= ' AND '.$basics['table'].'.'.$k.'="'.$v['default'].'"';
								} else {
									//$v['default'] = '"' . $v['default'] . '"';
									$search_text_arr[$v['head'].': '.$v['values'][$v['default']]] = 1;
									$r['sql_search'] .= ' AND '.$basics['table'].'.'.$k.'="'.$v['default'].'"';
								}
							}
						}
					} else if ($v['type'] == 'country') {
						global $countries;
						if ($_REQUEST[$k] == 'none') {
							$r['sql_search'] .= ' AND ('.$basics['table'].'.'.$k.'="" OR '.$basics['table'].'.'.$k.' IS NULL)';
							//keep search history
							$search_text_arr[$v['head'].': '.msg('none')] = 1;
						} else if($_REQUEST[$k] == 'all') {
							$r['sql_search'] .= ' AND ('.$basics['table'].'.'.$k.'!="" AND '.$basics['table'].'.'.$k.' IS NOT NULL)';
							//keep search history
							$search_text_arr[$v['head'].': '.msg('all')] = 1;
						} else if ($_REQUEST[$k] != '') {
							$r['sql_search'] .= ' AND '.$basics['table'].'.'.$k.'="'.$_REQUEST[$k].'"';
							//keep search history
							$search_text_arr[$v['head'].': '.$countries[$_REQUEST[$k]]] = 1;
						}
					} else if ($v['type'] == 'checkbox' || $v['type'] == 'C') {
						if ($fields[$k]['param2']['multi'] == 'Z' || $fields[$k]['param2']['multi'] == 'X') {
							$field_search = $k;
							if ($fields[$k]['param2']['multi'] == 'X') {
								$field_search = $k . '_cache';
							}
							$r['sql_search'] .= ' AND (';
							$search_text = array();
							foreach ($_REQUEST[$k] as $k4 => $v4) {
								$search_text[] = $v['values'][$v4];
								if ($k4 > 0) {
									$r['sql_search'] .= ' OR ';
								}
								$r['sql_search'] .= $basics['table'].'.'.$field_search.' LIKE "%:'.$v4.':%"';
							}
							$r['sql_search'] .= ' )';
						} else {
							if ($_REQUEST[$k]) {
								$r['sql_search'] .= ' AND '. $basics['table'].'.'.$k.' IN('.implode(',', $_REQUEST[$k]).')';
								$search_text = array();
								foreach ($_REQUEST[$k] as $k4 => $v4) {
									$search_text[] = $v['values'][$v4];
								}
							}
						}

						if ($search_text) {
							$search_text_arr[$v['head'].': ' . implode(',', $search_text)] = 1;
						}
					} else if ($v['type'] == 'daterange') {
						if ($v['default'] != trim($v['head'])) {
							$sep_dater = explode(' to ', urldecode($v['default']));
							//FROM_UNIXTIME
							if ($v['values'] == 'unix') {
								if (count($sep_dater) > 1) {
									if ($sep_dater[0] && $sep_dater[1]) {
										$r['sql_search'] .= ' AND FROM_UNIXTIME('.$basics['table'].'.'.$k.')>="'.date('Y-m-d', strtotime($sep_dater[0])).'" AND FROM_UNIXTIME('.$basics['table'].'.'.$k.')<="'.date('Y-m-d',strtotime($sep_dater[1])).'"';
									} else if (!$sep_dater[0] && $sep_dater[1]) {
										$r['sql_search'] .= ' AND FROM_UNIXTIME('.$basics['table'].'.'.$k.')<="'.date('Y-m-d', strtotime($sep_dater[1])).'"';
									} elseif ($sep_dater[0] && !$sep_dater[1]) {
										$r['sql_search'] .= ' AND FROM_UNIXTIME('.$basics['table'].'.'.$k.')>="'.date('Y-m-d', strtotime($sep_dater[0])).'"';
									}
								} else {
									if ($sep_dater[0]) {
										$r['sql_search'] .= ' AND FROM_UNIXTIME('.$basics['table'].'.'.$k.')="'.date('Y-m-d', strtotime($sep_dater[0])).'"';
									}
								}
							} else {
								if (count($sep_dater) > 1) {
									if ($sep_dater[0] && $sep_dater[1]) {
										if ($v['convert_date'] == 1) {
											$r['sql_search'] .= ' AND DATE('.$basics['table'].'.'.$k.')>="'.date('Y-m-d', strtotime($sep_dater[0])).'" AND DATE('.$basics['table'].'.'.$k.')<="'.date('Y-m-d',strtotime($sep_dater[1])).'"';
										} else {
											$r['sql_search'] .= ' AND ('.$basics['table'].'.'.$k.')>="'.date('Y-m-d', strtotime($sep_dater[0])).'" AND ('.$basics['table'].'.'.$k.')<="'.date('Y-m-d',strtotime($sep_dater[1])).'"';
										}
									} else if (!$sep_dater[0] && $sep_dater[1]) {
										if ($v['convert_date'] == 1) {
											$r['sql_search'] .= ' AND DATE('.$basics['table'].'.'.$k.')<="'.date('Y-m-d', strtotime($sep_dater[1])).'"';
										} else {
											$r['sql_search'] .= ' AND ('.$basics['table'].'.'.$k.')<="'.date('Y-m-d', strtotime($sep_dater[1])).'"';
										}
									} elseif ($sep_dater[0] && !$sep_dater[1]) {
										if ($v['convert_date'] == 1) {
											$r['sql_search'] .= ' AND DATE('.$basics['table'].'.'.$k.')>="'.date('Y-m-d', strtotime($sep_dater[0])).'"';
										} else {
											$r['sql_search'] .= ' AND ('.$basics['table'].'.'.$k.')>="'.date('Y-m-d', strtotime($sep_dater[0])).'"';
										}
									}
								} else {
									if ($sep_dater[0]) {
										if ($v['convert_date'] == 1) {
											$r['sql_search'] .= ' AND DATE('.$basics['table'].'.'.$k.')="'.date('Y-m-d', strtotime($sep_dater[0])).'"';
										} else {
											$r['sql_search'] .= ' AND ('.$basics['table'].'.'.$k.')="'.date('Y-m-d', strtotime($sep_dater[0])).'"';
										}
									}
								}
							}
							$search_text_arr[$v['head'].': '.$v['default']] = 1;
						} else {
							$add_linked = 1;//dont want to add linked
						}
					} else if ($v['type'] == 'autocomplete') {
						if ($v['save_name'] == 1) {
							$tmp = $v['default'];
							unset($v['default']);
							$v['default']['id'] = $tmp;
							$v['default']['name'] = $tmp;

							if ($v['table']) {
								$table = $v['table'];
							} else {
								$table = $basics['table'];
							}
							$r['sql_search'] .= ' AND ' . $table . '.' . $k . ' LIKE "' . $v['default']['name'] . '%"';
							$search_text_arr[$v['head'].': '.$v['default']['name']] = 1;
						} else {
							require_once PATH . 'modules/' . $v['entity'] . '.php';
							$fn = PREFIX . $v['entity'] . '_list';
							if ($v['list']) {
								$_REQUEST['type'] = $v['list'];
							}
							if (function_exists($fn) && $v['default']) {
								$tmp = $fn($v['default']);
								$id = $v['default'];
								unset($v['default']);
	
								$v['default']['id'] = $id;
								$v['default']['name'] = $tmp[$id];
								$r['sql_search'] .= ' AND ' . $basics['table'] . '.' . $k . '=' . $id;
								$search_text_arr[$v['head'].': '.$v['default']['name']] = 1;
							}
						}
					}
					//TODO check other type
				}
				//unset($_REQUEST[$k]);

				if ($add_linked != 1) {
					if ($v['type'] == 'checkbox') {
						if ($v['default']) {
							foreach ($v['default'] as $kx => $vx) {
								$r['linked'] .= '&'.$basics['entity_key'].'['.$k.'][]='.$vx;
							}
						}
					} else if ($v['type'] == 'autocomplete') {
						$r['linked'] .= '&'.$basics['entity_key'].'['.$k.']='.$v['default']['id'];
					} else {
						$v['default'] = str_replace(' ', '%20', $v['default']);
						$r['linked'] .= '&'.$basics['entity_key'].'['.$k.']='.urlencode($v['default']);
						$v['default'] = str_replace('%20', ' ', $v['default']);
					}
				}
			} else if ($v['skip'] == 1 && $_REQUEST[$k]) {
				$v['default'] = $_REQUEST[$k];
				if (is_array($_REQUEST[$k])) {
					foreach ($_REQUEST[$k] as $kr => $vr) {
						if (!is_array($vr)) {
							$r['linked'] .= '&'.$basics['entity_key'].'['.$k.']['.$kr.']='.urlencode($vr);							
						}
					}
				} else {
					$r['linked'] .= '&'.$basics['entity_key'].'['.$k.']='.urlencode($v['default']);
				}
			}
			//return field from fw
			$v['search'] = 1;
			if ($v['type'] == 'E') {
				$k_name = $k;
			} else {
				$k_name = $basics['entity_key'].'['.$k.']';
				if ($v['type'] == 'user') {
					$v['f'] = $k;
				}
			}

			$a = fw_form_item($k_name, $v, $basics);
			
			if ($v['type'] == 'daterange') {
				$v['head'] = '';
			}

			if (trim($v['head']) != '') {
				$semi = ': ';
			} else {
				$semi = ' ';
			}
			if ($v['search_show'] == '3') {
				$box_forms[$k.'_search'] = '<span class="fw-search_field">'.$a['field'].'</span>';
			} else {
				$box_forms[$k.'_search'] = '<span class="fw-search_field">'.$v['head'].$semi.$a['field'].'</span>';
			}
		}
	}

	//check show form for tabs
	if ($_REQUEST['search']) {// || $_POST['clear'] || $r['linked'] || $_REQUEST['search'] == 1
		//$r['linked'] .= '&search=1';
	}

	if ($_REQUEST[$basics['entity_key']]['adv'] == 1) {
		$r['linked'] .= '&'.$basics['entity_key'].'[adv]=1';
	}

	//sort by
	$search_sort_by = '';
	if ($_REQUEST[$basics['entity_key']]['sort_by']) {
		$r['sort'] .= '&'.$basics['entity_key'].'[sort_by]='.$_REQUEST[$basics['entity_key']]['sort_by'];
		if ($table['headers']['h']) {
			$get_key = array_search($_REQUEST[$basics['entity_key']]['sort_by'], $table['headers']['h']);
		}
		$search_sort_by .= msg('sort').': '.$table['header_def'][$get_key];
	}

	//sort order
	if ($_REQUEST[$basics['entity_key']]['sort_order']) {
		$r['sort'] .= '&'.$basics['entity_key'].'[sort_order]='.$_REQUEST[$basics['entity_key']]['sort_order'];
		$search_sort_by .= '['.$_REQUEST[$basics['entity_key']]['sort_order'].']';
	}

	if ($search_sort_by) {
		$search_text_arr[$search_sort_by] = 1;
	}

	//current page
	if ($_REQUEST[$basics['entity_key']]['page']) {
		$r['linked'] .= '&'.$basics['entity_key'].'[page]='.$_REQUEST[$basics['entity_key']]['page'];
	} else {
		$r['linked'] .= '&'.$basics['entity_key'].'[page]=0';
	}

	//clean linked
	if ($r['linked']) {
		$r['linked'] = str_replace(' ', '%20', $r['linked']);
	}

	if ($search_text_arr) {
		$r['search_text'] = implode(array_keys($search_text_arr), ', ');
	}

	if ($_REQUEST['button_name']) {
		$r['linked'] .= '&button_name=' . $_REQUEST['button_name'];
	}

	//create form and search box
	$r['form'] = '-';
	if ($entities[$entity]['search']['pattern_search_form'] != '') {
		//TODO show frame around search if we have single entity ||| class="ui-widget-content ui-corner-all
		if ($_REQUEST['mod'] != 'entities' && $basics['group_set'] != 1) {
			$box_class = 'ui-widget-content ui-corner-all gain-clean-content';
		} else {
			$box_class = '';
		}

		if (isset($entities[$entity]['search']['quick'])) {
			$entities[$entity]['search']['hide_form'] = 1;
		}

		//hide search form
		$hide = '';
		if ($entities[$entity]['search']['hide_form'] == 1 || $_SESSION[SESSION_A]['search_layout'] == 'C') {// && !$_POST['search'] && !$_POST['clear']
			$hide = ' hide';
		}
		$r['form'] = '
			<div id="'.$basics['entity_key'].'_search_form" style="margin-bottom: 10px;" class="'.$hide.'">
				<div id="fw-show_search_form_'.$basics['entity_key'].'" class="'.$box_class.'" style="position: relative;">
					<form id="fw-search_form_'.$basics['entity_key'].'" action="'.$entities[$entity]['search']['action_search_form'].'" method="post">
					<input type="hidden" name="search" value="'.msg('fw-search').'"/>';

		$txt = $entities[$entity]['search']['pattern_search_form'];
		if (strstr($txt, 'start_search_advanced') && strstr($txt, 'end_search_advanced')) {
			$adv = 0;
			$class_adv = ' hide';
			if ($_REQUEST[$basics['entity_key']]['adv'] == 1) {
				$class_adv = '';
				$adv = 1;
			}
			$txt = '<a class="fg-button ui-state-default fg-button-icon-solo ui-corner-all search_advanced_icon'.$class_adv.'" style="padding: 8px; position: absolute; right: 0px; top: 2px;"><span class="ui-icon ui-icon-plusthick" title="'.msg('search_advanced').'"></span></a>'.$txt;
			$txt = str_replace('{start_search_advanced}', '<div class="search_advanced'.$class_adv.'">', $txt);
			$txt = str_replace('{end_search_advanced}', '<input type="hidden" id="adv_search_'.$basics['entity_key'].'" name="'.$basics['entity_key'].'[adv]" value="'.$adv.'"/></div>', $txt);
			$icon = 1;
		}

		if (strstr($txt, '{search_history_icon')) {
			$r['history_icon'] = 1;
			$history_display = 1;
			$txt = str_replace('{search_history_icon}', '', $txt);
		}

		if ($box_forms) {
			foreach ($box_forms as $ka => $va) {
				$txt = str_replace('{'.$ka.'}', $va, $txt);
			}
		}

		if (strstr($txt, '{search_limit_perpage}')) {
			if ($_REQUEST[$basics['entity_key']]['limit']) {
				$default_limit = $_REQUEST[$basics['entity_key']]['limit'];
			} else {
				$default_limit = $_SESSION[SESSION_A]['result_per_page'];
			}

			$search_limit_perpage = '<span class="fw-search_field hide">'.form_select($basics['entity_key'].'[limit]', array('default' => $default_limit, 'param2' => 'N', 'values' => '1:5:10', 'req' => 1)).'</span>';
			$txt = str_replace('{search_limit_perpage}', $search_limit_perpage, $txt);
		}

		$txt = str_replace('{search_button}', '<input type="submit" class="btn medium blue awesome btn-search" name="search" value="'.msg('fw-search').'" />', $txt);
		if ($_REQUEST['clear'] == msg('fw-clear')) {
			$txt = str_replace('{clear_button}', '<input type="submit" class="btn medium gray awesome clear_button btn-clear" name="clear" value="'.msg('fw-default').'" />', $txt);
		} else { 
			$txt = str_replace('{clear_button}', '<input type="submit" class="btn medium gray awesome clear_button btn-clear" name="clear" value="'.msg('fw-clear').'" />', $txt);
		}

		$txt = str_replace('{reset_button}', '<input type="reset" class="btn medium awesome" name="reset" value="'.msg('fw-reset').'" />', $txt);

		$r['form'] .= $txt;
		//show search history icon
		$r['form'] .= '</form></div>';
		if ($ajax) {
			$r['form'] .= $ajax; //for advanced search
		} else {
			$r['form'] .= $script_search.'
		<script type="text/javascript">
			var adv = $("#adv_search_'.$basics['entity_key'].'").val();
			if (adv == 0) {
				$("#fw-show_search_form_'.$basics['entity_key'].' .search_advanced").hide();
			}
			'.$script_class.'
			$("#fw-show_search_form_'.$basics['entity_key'].' .search_advanced_icon").click(function(){
				adv = $("#adv_search_'.$basics['entity_key'].'").val();
				if (adv == 0) {
					$("#adv_search_'.$basics['entity_key'].'").val(1);
					$(this).find("span").removeClass("ui-icon-plusthick").addClass("ui-icon-minusthick");
				} else if (adv == 1) {
					$("#adv_search_'.$basics['entity_key'].'").val(0);
					$(this).find("span").removeClass("ui-icon-minusthick").addClass("ui-icon-plusthick");
				}
				
				$("#fw-show_search_form_'.$basics['entity_key'].' .search_advanced").toggle("fast");
			});
			//clear form click!!!
			$("#fw-search_form_'.$basics['entity_key'].' .clear_button").click(function(){
				item_selected["'.$basics['entity_key'].'"] = new Array();
				//for clear lookup search
				$("#fw-search_form_'.$basics['entity_key'].' input[type=hidden]").val("");
				$("a.clientIDbutton").hide();

				$("#fw-search_form_'.$basics['entity_key'].' select[name=\''.$basics['entity_key'].'[limit]\']").val("'.$_SESSION[SESSION_A]['result_per_page'].'");
				$("#fw-search_form_'.$basics['entity_key'].' input[class=ui-rangepicker-input]").each(function(){
					$(this).val($(this).attr("def"));
				});
				$("#fw-search_form_'.$basics['entity_key'].' select[name!=\''.$basics['entity_key'].'[limit]\'], #fw-search_form_'.$basics['entity_key'].' input[class != ui-rangepicker-input]").clearFields();

				if ($(this).attr("value") == "default" && "'.(int)$basics['group_url'].'" != 1 && "' . (int)$basics['permanent_group'] . '" != 1) {
					//set default search
					$("#fw-search_form_'.$basics['entity_key'].' select[default_search!=undefined]").each(function(){
						$(this).val($(this).attr("default_search"));
					});
					$("#fw-search_form_'.$basics['entity_key'].' input[default_search!=undefined][type!=submit]").each(function(){
						$(this).val($(this).attr("default_search"));
					});
				}
			});

			$("#fw-search_form_'.$basics['entity_key'].'").ajaxForm({
				target: "#'.$basics['refresh_action_ajax'].'",
			  	success: function(){//ui-state-default
			  		fw_effect_loading("","",1000);
			  		var entity_index = $("li#'.$basics['entity_key'].'_li").attr("rel")*1;
			  		$("#tab_menu_search_result").tabs("select", entity_index);
			  		item_selected["'.$basics['entity_key'].'"] = new Array();
				},
			});
		</script>';
		}

		if ($_REQUEST['clear'] == msg('fw-clear') || $_REQUEST['clear'] == msg('fw-default') || $not_default_search == 0 || !$_POST['search']) {
			//dont show button
		} else {
			if ($basics['group_url'] == 1) {
				$r['form'] .= '<div id="fw-show_search_form_'.$basics['entity_key'].'2">';
				
				//check permission for this group
				$sql = SQL('SELECT manage_access, manage_permission, added_by
				FROM gain_fw_entity_group
				WHERE removed IS NULL
				AND group_token=%s
				ORDER BY permanent_order DESC', $basics['entity_key']);
				$row = $db->GetRow($sql);
				if ($row['added_by'] == $_SESSION[SESSION_L] || $row['manage_permission'] == 'full') {
					$r['form'] .= ' <input type="button" name="update_filter_group" value="'.msg('Update group to this filter').'" class="btn big blue awesome" onclick="fw_manage_entity_group(this,\''.$basics['entity'].'\', \''.$basics['entity_key'].'\',\'\',\'add_to_group\',\''.$basics['search']['search_history_token'].'\',fw_get_item(this,\''.$basics['entity_key'].'\'),1)" style="margin-left: 5px; margin-top: 5px;"/>';
				}
				$r['form'] .= $basics['search']['search_history_token'].' <input style="margin-left: 5px; margin-top: 5px;" type="button" name="filter_as_group" value="'.msg('Create group from this filter').'" class="btn big blue awesome" onclick="fw_manage_entity_group(this,\''.$basics['entity'].'\', \''.$basics['entity_key'].'\',\'\',\'add_to_group\',\''.$basics['search']['search_history_token'].'\',fw_get_item(this,\''.$basics['entity_key'].'\'),1)"/><br class="clr"/>';
				$r['form'] .= '</div>';
			} else if ($history_display == 1 && $basics['entity'] == $basics['entity_key']) {
				$r['form'] .= '<div id="fw-show_search_form_'.$basics['entity_key'].'2">';
				if ($basics['permanent_group'] != 1) {
					$r['form'] .= ' <input type="button" rel="0" mod="'.$_REQUEST['mod'].'" search_entity="'.$basics['entity_key'].'" name="set_as_default" value="'.msg('Set as default').'" class="btn big blue awesome" onclick="set_search_default(this,\''.$basics['search']['search_history_token'].'\');" style="margin-left: 5px; margin-top: 5px;"/>';
				}
				if ($basics['manage_group_set'] != -1) {
					$r['form'] .= ' <input type="button" name="filter_as_group" value="'.msg('Filter as group').'" class="btn big blue awesome" onclick="fw_manage_entity_group(this,\''.$basics['entity'].'\', \''.$basics['entity_key'].'\',\'\',\'add_to_group\',\''.$basics['search']['search_history_token'].'\',fw_get_item(this,\''.$basics['entity_key'].'\'),1)"/><br class="clr"/>';
				}
				$r['form'] .= '</div>';
			}
		}
		$r['form'] .= '</div>';
	}

	//TODO re set it
	//limit perpage
	if ($default_limit) {
		$r['linked'] .= '&'.$basics['entity_key'].'[limit]='.$default_limit;
	}
	return $r;
}

/**
 * return sql
 * @return unknown_type
 */
function fw_search_result(&$entities, $entity, &$search, $sql_limit_page = '', $sql_add = ''){
	global $db, $search_cache, $fav_all, $config, $cm_menu;
	$basics = $entities[$entity]['basics'];
	$fields = $entities[$entity]['fields'];

	if ($entities[$entity]['search']['search_fields'] && !$_REQUEST['post_form']) {
		foreach ($entities[$entity]['search']['search_fields'] as $k => $v) {
			unset($_REQUEST[$k]);
		}
	}

	$sql_search = $search['sql_search'];

	if ($config['search_cache'][$entity]) {
		$file = 'files/cache/search_cache_'.$entity.'.php';
		if (file_exists($file)) {
			require_once($file);
		}
	}

	//cleanup param
	$cleanVar = fw_data_cleanup($fields, $basics);
	$fields  = $cleanVar[0];
	$basics  = $cleanVar[1];

	//gen sql
	if ($entities[$entity]['table']['headers2']['info']) {
		//add checkbox with id key
		if ($entities[$entity]['basics']['actions'] && $entities[$entity]['table']['set_actions'] != 1) {
			
			//beem create 2011-08-24
			//check header_def, h, search_result
			$entities[$entity]['table']['headers2']['info']['checkbox']['header_def'] = '<img src="im/checkbox_none.png" onclick="fw_check_items(this, \''.$basics['entity_key'].'\')" class="check_items_'.$basics['entity_key'].' fw-point" rel="0"/>';
			$entities[$entity]['table']['headers2']['info']['checkbox']['h'] = 's_checkbox';
			$check_item = '<img onclick="fw_check_item(this, \''.$basics['entity_key'].'\');" src="im/checkbox_none.png" id="check_item_'.$basics['entity_key'].'_{entity|'.$entities[$entity]['basics']['key'].'}" class="check_item_'.$basics['entity_key'].' fw-point" rel="0" item_id="{entity|'.$entities[$entity]['basics']['key'].'}"/>';
			$entities[$entity]['table']['headers2']['info']['checkbox']['search_result'] = $check_item;
			if (!$entities[$entity]['table']['headers2']['info']['checkbox']['width']) {
				$entities[$entity]['table']['headers2']['info']['checkbox']['width'] = 5;
			}
			$entities[$entity]['table']['set_actions'] = 1;
		}
		$f = array();
		//add last column [options]
		if ($entities[$entity]['table']['search_result_options']) {
			//add last column
			$options = '';
			$tpl_option = array('detail', 'edit', 'edit_popup', 'duplicate', 'duplicate_popup', 'delete');
			//edit popup show popup else show new page
			if (count($entities[$entity]['table']['search_result_options']) > 0) {
				foreach ($entities[$entity]['table']['search_result_options'] as $option) {
					if (in_array($option, $tpl_option)) {
						if ($option == 'detail') {//show
							$options .= '<a class="clickMe" href="#'.msg('detail').'{entity|'.$entities[$entity]['basics']['key'].'}" rel="{entity|'.$entities[$entity]['basics']['key'].'}" item="'.$entities[$entity]['basics']['entity'].'" onclick="runItemDetails(this);"><img src="im/info.png" title="'.msg('detail').'" /></a> ';
						} else {//check
							$options .= '{'.$option.'} ';
							$inf_function[$option] = 1;
						}
					} else {
						$opt_function = PREFIX.'option_'.$option;
						$inf_function['option_'.$option] = 1;
						if (function_exists($opt_function)) {
							$options .= '{option_'.$option.'} ';
						} else {
							$options .= $opt_function;
						}
					}
				}
			}
			
			//get entity details
			$entity_info = gain_entity_get_entity_detail($entity);
			$entity_check = $entity_info['mod_main'];
			if ($cm_menu['M'][$entity_check]['P'] == 1) {
				if ($_SESSION[SESSION_P]['permissions']['menu'][$entity_check]['permission'] == 1) {
					$options .= ' <a href="#permission{entity|'.$entities[$entity]['basics']['key'].'}" onclick="fw_manage_permission(this, \''.$entity.'\', \'{entity|'.$entities[$entity]['basics']['key'].'}\')"><img src="im/permission.png"/></a>';
				} else {
					$f['table']['gain_entity_permission'] = 1;
					$f['select']['gain_entity_permission.p_view'][] = 1;
					$f['select']['gain_entity_permission.p_modify'][] = 1;
					$f['select']['gain_entity_permission.p_delete'][] = 1;
					
					$f['where']['gain_entity_permission.entity_id='.$basics['table'].'.'.$basics['key']] = 1;
					$f['where']['gain_entity_permission.access_type="D"'] = 1;					
					$f['where']['gain_entity_permission.access_id='.$_SESSION[SESSION_A]['department']] = 1;
					$f['where']['gain_entity_permission.entity="'.$entity.'"'] = 1;
					$f['where']['gain_entity_permission.p_view=1'] = 1;
				}		
			}
			
			if ($entities[$entity]['table']['set_options'] != 1) {
				//beem create 2011-08-24
				//check header_def, h, search_result
				$entities[$entity]['table']['headers2']['info']['options']['header_def'] = msg('options');
				$entities[$entity]['table']['headers2']['info']['options']['h'] = 's_option';
				$entities[$entity]['table']['headers2']['info']['options']['search_result'] = $options;
				if (!$entities[$entity]['table']['headers2']['info']['options']['width']) {
					$entities[$entity]['table']['headers2']['info']['options']['width'] = 60;
				}
				if ($entities[$entity]['table']['shorthand_detail']) {
					$entities[$entity]['table']['headers2']['info']['shorthand']['search_result'] = $entities[$entity]['table']['shorthand_detail'];
				}
				$entities[$entity]['table']['set_options'] = 1;
			}
		}
		
		if (!$search_cache[$entity] || SET_SEARCH_OPTION == 1) {
			//change sql_query_add_table to array
			//$basics['sql_query_add_field'] = array(
			//'removed' : same with main table
			//,'gain_client.id_client'); : other table
			if ($basics['sql_query_add_field']) {
				if (is_array($basics['sql_query_add_field'])) {
					foreach ($basics['sql_query_add_field'] as $k => $v) {
						if (strstr('.', $v)) {
							$f1 = explode('.', $v);
							$f['select'][$v][] = 1;
							$f['table'][$f1[0]] = 1; //need to add condition for cross table
						} else {
							$f['select'][$basics['table'].'.'.$v][] = 1;
						}
					}
				} else {
					if (strstr('.', $basics['sql_query_add_field'])) {
						$f1 = explode('.', $basics['sql_query_add_field']);
						$f['select'][$basics['sql_query_add_field']][] = 1;
						$f['table'][$f1[0]] = 1;
					} else {
						$f['select'][$basics['sql_query_add_field']][] = 1;
						//$change_pattern[$basics['sql_query_add_field']][$matches[1][$k2]] = $p[1];
					}
				}
			}

			//beem add custom field,table and condition
			if ($basics['sql_query_add_table']) {
				if (is_array($basics['sql_query_add_table'])) {
					foreach ($basics['sql_query_add_table'] as $k => $v) {
						$f['table'][$v] = 1;
					}
				} else {
					$f['table'][$basics['sql_query_add_table']] = 1;
				}
			}
			if ($basics['sql_query_add_condition']) {
				if (is_array($basics['sql_query_add_condition'])) {
					foreach ($basics['sql_query_add_condition'] as $k => $v) {
						$f['where'][$v] = 1;
					}
				} else {
					$f['where'][$basics['sql_query_add_condition']] = 1;
				}
			}
			$f['table'][$basics['table']] = 1;
			//add key for select
			$f['select'][$basics['table'].'.'.$basics['key']][] = 1;
			$show_primary_fields = 0;
			//need for check permission
			if ($basics['set_log'] != 0) {
				$f['select'][$basics['table'].'.added_by'][] = 1;
			}

			//foreach ($entities[$entity]['table']['search_result'] as $k => $v) {
			foreach ($entities[$entity]['table']['headers2']['info'] as $kx => $info) {
				$v = $info['search_result'];	
				$matches = array();
				preg_match_all('/{(.*)}/Usi', $v, $matches);
				if ($matches) {
					//for primary key $basics['key']
					foreach ($matches[0] as $k2 => $v2) {
						if ($k2 == '{show_fav}') {
							$inf_function['show_fav'] = 1;
						}
						$p = array();
						$p = explode('|',substr($v2,1,-1));
						if ($p[0] == 'primary_fields') {
							$show_primary_fields = 1;
						} else if ($p[0] == 'detail') {
							//for short hand detail
							$f['select'][$basics['table'].'.'.$p[1]][$matches[1][$k2]] = 1;
							$change_pattern[$basics['table'].'.'.$p[1]][$matches[1][$k2]] = 'shorthand_'.$p[1];

							$fields_detail[$matches[1][$k2]] = $p[1];//set for get result by fields
							$shorthand[$matches[1][$k2]] = $p[1];
						} else if ($p[0] == 'entity' || strtoupper($p[0]) == 'E') {
							//{entity|co_name}
							//{entity|id_client} check lookup condition
							if ($fields[$p[1]]['lookup'] || $fields[$p[1]]['LU']) {//clean LU
								if (strstr($fields[$p[1]]['lookup']['table'], ' AS ')) {
									$e = explode(' AS ', $fields[$p[1]]['lookup']['table']);
									if (is_array($fields[$p[1]]['lookup']['display'])) {
										$f['select'][$basics['table'].'.'.$p[1]][] = 1;
										$display = 'CONCAT(';
										foreach ($fields[$p[1]]['lookup']['display'] as $k3 => $v3) {
											if ($k3 > 0) {
												$display .= '," ", ';
											}
											$display .= 'IF(ISNULL('.$e[1].'.'.$v3.'),"", '.$e[1].'.'.$v3.')';
										}
										$display .= ')';
										$f['select'][$display][$matches[1][$k2]] = 1;
										$change_pattern[$display][$matches[1][$k2]] = $p[1];
									} else {
										$f['select'][$e[1].'.'.$fields[$p[1]]['lookup']['display']][$matches[1][$k2]] = 1;
										$f['select'][$basics['table'].'.'.$p[1]][] = 1;
									}
									$f['table'][$fields[$p[1]]['lookup']['table']] = 1;
									$f['where'][$basics['table'].'.'.$p[1].'='.$e[1].'.'.$fields[$p[1]]['lookup']['id']] = 1;
								} else {
									if (is_array($fields[$p[1]]['lookup']['display'])) {
										$f['select'][$basics['table'].'.'.$p[1]][] = 1;
										$display = 'CONCAT(';
										foreach ($fields[$p[1]]['lookup']['display'] as $k3 => $v3) {
											if ($k3 > 0) {
												$display .= '," ", ';
											}
											$display .= $fields[$p[1]]['lookup']['table'].'.'.$v3;
										}
										$display .= ')';
										$f['select'][$display][$matches[1][$k2]] = 1;
										$change_pattern[$display][$matches[1][$k2]] = $p[1];
									} else {
										$f['select'][$fields[$p[1]]['lookup']['table'].'.'.$fields[$p[1]]['lookup']['display']][$matches[1][$k2]] = 1;
										//if new table diff from main need to set another condition
										if ($fields[$p[1]]['lookup']['table'] != $basics['table']) {
											$f['table'][$fields[$p[1]]['lookup']['table']] = 1;
											$f['select'][$basics['table'].'.'.$p[1]][] = 1;
											$f['where'][$basics['table'].'.'.$p[1].'='.$fields[$p[1]]['lookup']['table'].'.'.$fields[$p[1]]['lookup']['id']] = 1;
										}
									}
								}
							} else {
								if ($fields[$p[1]]['type'] == 'file') {
									if (!is_array($fields[$p[1]]['param2'])) {
										$f['select'][$basics['table'].'.'.$p[1].'_updated'][] = 1;
										$f['select'][$basics['table'].'.'.$p[1].'_updated_by'][] = 1;
										$f['select'][$basics['table'].'.'.$p[1]][$matches[1][$k2]] = 1;
										$fields_detail[$matches[1][$k2]] = $p[1];
									} else {
										$f['select'][$basics['table'].'.'.$p[1]][$matches[1][$k2]] = 1;
										$fields_detail[$matches[1][$k2]] = $p[1];
									}
								} else {
									$f['select'][$basics['table'].'.'.$p[1]][$matches[1][$k2]] = 1;
									$fields_detail[$matches[1][$k2]] = $p[1];
								}
							}
						} else if ($p[0] == 'column' || strtoupper($p[0]) == 'C') {
							//for dont set fields
							//ex1:{column|client_name}
							//ex2:{column|gain_client.id_client|client_name}
							//ex3{detail|gain_client_people.id_title|title}
							//ex4{detail|title}

							//ex5{column|gain_dsb.disbursement_type=gain_dsb_category.id_di_ca|gain_dsb_category.category_name}
							$n = array();
							if (strstr($p[1], '=')) {
								$m = explode('=', $p[1]);
								if ($m) {
									foreach ($m as $k => $v) {
										if (strstr($v, '.')) {
											$o = explode('.', $v);
											$f['table'][$o[0]] = 1;
										}
									}
								}
								$f['select'][$p[2]][$matches[1][$k2]] = 1;
								$f['where'][$p[1]] = 1;
								if ($p[0] == 'detail') {
									$head_details[$matches[1][$k2]] = $p[1];
								}
							} else {
								if (strstr($p[1], '.')) {
									$n = explode('.', $p[1]);
									$f['select'][$n[0].'.'.$p[2]][$matches[1][$k2]] = 1;
									$f['table'][$n[0]] = 1;
									$f['where'][$p[1].'='.$basics['table'].'.'.$n[1]] = 1;
									if ($p[0] == 'detail') {
										$head_details[$matches[1][$k2]] = $n[1];
									}
								} else {
									$f['select'][$basics['table'].'.'.$p[1]][$matches[1][$k2]] = 1;
									if ($p[0] == 'detail') {
										$head_details[$matches[1][$k2]] = $p[1];
									}
								}
							}
						} else if ($p[0] == 'function' || strtoupper($p[0]) == 'F') {
							//set another array for get data after get query,,,
							//try to return values after get all data
							//{function|phone|column=table.test|column=id_company|style=icon|aaa=bbb}
							//s_ => static param
							//{function|phone|^phone=phone_default|style=icon|aaa=bbb}
							//TODO
							//column in case that we need to get value from database
							//$p[1] is function name
							//set function
							$function_name ='plug_'.$p[1];
							++$i;
							$inf_function[$function_name][$k . $i] = $matches[1][$k2];
							//get another column
							for ($np = 2; $np < count($p); $np++) {
								$n = array();
								if (strstr($p[$np], '=')) { //^phone=phone_detail
									//set static param
									$n = explode('=', $p[$np]);
									$n0 = $n[0];
									if ($n[0]{0} == '^') { //$n[0]=phone, $n[1]=phone_detail
										$n0 = substr($n[0], 1);
										//cross table
										if (strstr($n[1], '.')) {//^phone=gain_client.phone_default
											$n1 = explode('.', $n[1]);
											//set select for every fields
											$f['select'][$n[1]][] = 1;
											$f['table'][$n1[0]] = 1;
											$n[1] = $n1[0].'__'.$n1[1];
										} else {
											$f['select'][$basics['table'].'.'.$n[1]][] = 1;
											$n[1] = $basics['table'].'__'.$n[1];
										}
									}
									unset($n[0]);
									$params[$function_name][$k.$i][$n0] = implode('=', $n);
								}
							}
						}
					}
				}
			}

			//set cache params
			$params_cache = 'array(';
			if ($params) {
				foreach ($params as $k => $v) {
					$params_cache .= '
	\''.$k.'\' => array(';
					if ($v) {
						foreach ($v as $k2 => $v2) {
							$params_cache .= '
		\''.$k2.'\' => array(';
							if ($v2) {
								foreach ($v2 as $k3 => $v3) {
									$params_cache .= '
			\''.$k3.'\' => \''.$v3.'\',';
								}
							}
							$params_cache .= '),
			';
						}
					}
					$params_cache .= '),
					';
				}
			}
			$params_cache .= ');';

			//set query for primary fields
			$param_fields = fw_check_param_field($fields, 'primary_field');
			if ($param_fields['primary_field']) {
				$show_primary_field = '';
				foreach ($param_fields['primary_field'] as $k => $v) {
					if ($fields[$v]['primary_field_pattern'] != '') {
						$primary_fields['field_'.$v] = $fields[$v]['primary_field_pattern'];
					} else {
						$primary_fields['field_'.$v] = 1;
					}
					$show_primary_field .= ' {field_'.$v.'}';
					if ($fields[$v]['type'] == 'name') {
						$display = $basics['table'].'.'.$v.'_display';

						$f['select'][$display]['field_'.$v] = 1;
						$change_pattern[$display]['field_'.$v] = 'field_'.$v;
					} else if ($fields[$v]['lookup']) {
						if (is_array($fields[$v]['lookup']['display'])) {
							$display = 'CONCAT_WS(" "';
							foreach ($fields[$v]['lookup']['display'] as $k3 => $v3) {
								$display .= ','.$fields[$v]['lookup']['table'].'.'.$v3;
							}
							$display .= ')';
							$f['select'][$display]['field_'.$v] = 1;
							$change_pattern[$display]['field_'.$v] = 'field_'.$v;
						} else {
							$f['select'][$fields[$v]['lookup']['table'].'.'.$fields[$v]['lookup']['display']]['field_'.$v] = 1;
						}

						$f['table'][$fields[$v]['lookup']['table']] = 1;
						$f['where'][$fields[$v]['lookup']['table'].'.'.$v.'='.$basics['table'].'.'.$v] = 1;
						$change_pattern[$fields[$v]['lookup']['table'].'.'.$fields[$v]['lookup']['display']]['field_'.$v] = 'field_'.$v;
					} else {
						$f['select'][$basics['table'].'.'.$v]['field_'.$v] = 1;
						$change_pattern[$basics['table'].'.'.$v]['field_'.$v] = 'field_'.$v;
					}
				}
			}
			//set replace for {primary_fields} : shorthand details
			if ($show_primary_fields == 1) {
				$replace_alias['{primary_fields}'] = $show_primary_field;
			}
			//set query
			if ($f) {
				$sql .= 'SELECT {items}';
				//$sql_all = 'COUNT('.$basics['table'].'.'.$basics['key'].')';
				$sql_all = 'COUNT(1)';
				if ($f['select']) {
					//create pattern here!!!
					//set alias and replace it
					$k_qry = 0;
					foreach ($f['select'] as $k => $val) {
						if ($val) {
							foreach ($val as $v => $v2) {
								//set field name for query
								if (!strstr($k, 'IF(') && !strstr($k, ' AS ')) {
									$fields_alias = str_replace('.', '__', $k);
									if (isset($change_pattern[$k][$v])) {
										$fields_alias = $change_pattern[$k][$v];
									}
								
									//check sql_item
	//								$sql_item .= $k.' AS '.$fields_alias;
									$sql_item_arr[$k.' AS '.$fields_alias] = 1;
									//set to array
								} else {
									$sql_item_arr[$k] = 1;
								}
								if ($fields_detail[$v]) {
									//if ($shorthand[$v] == 1) $replace_alias['{'.$v.'}'] =
									//$fields[$fields_detail[$v]]['head'].': {'.$fields_alias.'}';
									$replace_alias['{'.$v.'}'] = '{'.$fields_alias.'}';
									$fields_info[$fields_alias] = $fields_detail[$v];
									if ($shorthand[$v]) {
										$short_detail[$fields_alias] = $v;
									}
								} else {
									$replace_alias['{'.$v.'}'] = '{'.$fields_alias.'}';
								}
							}
						}
					}

					if ($fields_info) {
						$fields_info_cache = 'array(';
						foreach ($fields_info as $k => $v) {
							$fields_info_cache .= '\''.$k.'\' => \''.$v.'\',';
						}
						$fields_info_cache .= ');';
					}

					//set replace for function
					if ($inf_function) {
						$inf_function_cache = 'array(';
						foreach ($inf_function as $k => $v){
							if (!is_array($v)) {
								$inf_function_cache .= '\''.$k.'\' => \''.$v.'\',';
							} else {
								if ($v) {
									$inf_function_cache .= '\''.$k.'\' => array(';
									foreach ($v as $k2 => $v2) {
										$inf_function_cache .= '\''. $k2 . '\' => \''.$v2.'\',';
										$replace_alias[$v2] = ''.$k2.'_'.$k.'';
									}
									$inf_function_cache .= '),';
								}
							}
						}
						$inf_function_cache .= ');';
					}

					//add verified fields
					if ($basics['verify'] == 1 && $basics['show_tab'] != 1) {
//						$sql_item .= ', '.$basics['table'].'.verified';
						$sql_item_arr[$basics['table'].'.verified'] = 1;
					}
					//gen pattern with new field name[alias]
					//foreach ($entities[$entity]['table']['search_result'] as $k2 => $v2) {
					foreach ($entities[$entity]['table']['headers2']['info'] as $k2 => $info) {
						$v2 = $info['search_result'];
						$pattern[$k2] = str_replace(array_keys($replace_alias),array_values($replace_alias), $v2);
					}
				}

				if ($f['table']) {
					//TODO beem
					if ($basics['sql_query_add_table_extra']) {
						foreach ($basics['sql_query_add_table_extra'] as $k2 => $v2) {
							unset($f['table'][$k2]);
							$f['table'][$k2 . ' '. $v2] = 1;
						}
					}
					$sql .= ' FROM '.implode(', ', array_keys($f['table']));
				}

				//for mail table check id_key>0
				$sql .= ' WHERE ';
				if ($basics['key_string'] == 1) {
					$sql .= ' 1=1';
				} else {
					$sql .= $basics['table'].'.'.$basics['key'].'>0';
				}

				//for main table check removed fields
				if ($basics['log_removed'] == 1) {
					$sql .= ' AND '.$basics['table'].'.removed IS NULL';
				}
				//add where condition
				$search_sql = '';
				if ($f['where']) {
					$sql .= ' AND '.implode(' AND ', array_keys($f['where']));
				}

				//set query
				if ($basics['actions']) {
					$sql_actions = str_replace('{items}', $basics['table'].'.'.$basics['key'], $sql);
				}
				$sql_list = str_replace('{items}', implode(', ', array_keys($sql_item_arr)), $sql);
				$sql_count = str_replace('{items}', $sql_all, $sql);
				$sql_search_id = str_replace('{items}', 'GROUP_CONCAT(' . $basics['table'].'.'.$basics['key'] . ')', $sql);
				//keep sql to cache file with this name
				$pattern_cache = 'array(';
				foreach ($pattern as $k => $v) {
					if (++$kp > 1) {
						$pattern_cache .= ',
	';
					}
					$pattern_cache .= '\''.addcslashes($v, '\'').'\'';
				}
				$pattern_cache .= ');';

				$primary_fields_cache = ' array(';
				if ($primary_fields) {
					foreach ($primary_fields as $k => $v) {
						$primary_fields_cache .= '
	\'' . $k . '\' => \'' . $v . '\',';
					}
				}
				$primary_fields_cache .= ');';

				$content = '<?php
	$search_cache[\''.$entity.'\'][\'set_actions\'] =\''.$entities[$entity]['table']['set_actions'].'\';
	$search_cache[\''.$entity.'\'][\'list\'] = \''.$sql_list.'\';
	$search_cache[\''.$entity.'\'][\'count\'] = \''.$sql_count.'\';
	$search_cache[\''.$entity.'\'][\'actions\'] = \''.$sql_actions.'\';
	$search_cache[\''.$entity.'\'][\'pattern\'] = '.$pattern_cache.'
	$search_cache[\''.$entity.'\'][\'inf_function\'] = '.$inf_function_cache.'
	$search_cache[\''.$entity.'\'][\'fields_info\'] = '.$fields_info_cache.'
	$search_cache[\''.$entity.'\'][\'params\'] = '.$params_cache.'
	$search_cache[\''.$entity.'\'][\'primary_fields\'] = '.$primary_fields_cache.'
?>';
				file_put_contents('files/cache/search_cache_'.$entity.'.php', $content);
			}
		} else {
			$set_actions = $search_cache[$entity]['set_actions'];
			$sql_list = $search_cache[$entity]['list'];
			$sql_count = $search_cache[$entity]['count'];
			$sql_actions = $search_cache[$entity]['actions'];
			$pattern = $search_cache[$entity]['pattern'];
			$inf_function = $search_cache[$entity]['inf_function'];
			$fields_info = $search_cache[$entity]['fields_info'];
			$params = $search_cache[$entity]['params'];
			$primary_fields = $search_cache[$entity]['primary_fields'];
		}

		//summary sql
		if ($sql_search) {
			$sql_list .= $sql_search;
			$sql_count .= $sql_search;
			$sql_actions .= $sql_search;
			$sql_search_id .= $sql_search;
		}

		//generate sql
		if ($sql_add) {
			$sql_list .= $sql_add;
			$sql_count .= $sql_add;
			$sql_actions .= $sql_add;
			$sql_search_id .= $sql_add;
		}
	}

	if ($basics['actions']) {
		$rsl_all = $db->GetCol($sql_actions, 'fw');
		$item_all = count($rsl_all);
	}

	if ($_REQUEST['link'] != 'detail' && $_REQUEST['link'] != 'edit') {
		$rsl = $db->GetArray($sql_list . $sql_limit_page, 'fw');
	}

	if ($rsl) {//no data no need to get to function
		if ($basics['actions']) {
			
			$cnt_token = 0;
			foreach ($basics['actions'] as $act_name => $val) {
				if ($val) {
					foreach ($val as $k => $v) {
						if (strstr($v, '{token}')) {
							++$cnt_token;
						}
					}
				}
			}
			if ($cnt_token > 0) {
				if ($_REQUEST['search_token']) {
					$sql = SQL('SELECT search_token, search_checksum 
					FROM gain_fw_search_cache 
					WHERE added_by=%d
					AND search_token=%s', $_SESSION[SESSION_L], $_REQUEST['search_token']);//$sql_search_id, 
					$search_token_get = $db->GetRow($sql);
				}
				if (!$search_token_get) {	
					$rsl_all = $db->GetCol($sql_actions, 'fw');
					$item_all = count($rsl_all);

					$search_token = md5(time().$basics['entity'] . $_SESSION[SESSION_L]);
					$search_name = $basics['entity'];
	
					$sql = SQL('INSERT INTO gain_fw_search_cache(search_token, search_name, search_id, search_checksum, added, added_by) VALUES(%s,%s,%s,%d,NOW(),%d)',
					$search_token, $search_name, $sql_search_id, $item_all, $_SESSION[SESSION_L]);
					$db->Execute($sql, 'fw');
				} else {
					$search_token = $search_token_get['search_token'];
					$item_all = $search_token_get['search_checksum'];
				}
			}
		} else {
			$item_all = $db->GetOne($sql_count, 'fw');
		}

		$search['linked'] .= '&search_token=' . $search_token;
		if ($inf_function){//get data from function
			foreach ($rsl as $k => $v) {
				$item_id_all[] = $v[$basics['table'].'__'.$basics['key']];
			}
			$info = array('fields' => $fields, 'basics' => $basics, 'allResults' => $rsl, 'item_id_all' => $item_id_all);
			foreach ($inf_function as $function_name => $param) {
				//prepare function
				$fn = PREFIX . $function_name;
				//call function & //check function exist
				if (function_exists($fn)) {
					//check param
					foreach ($rsl as $k => $v) {
						$info['row'] = $v;
						//assign param
						if ($param == 1) {
							if ($params[$function_name]) {
								foreach ($params[$function_name] as $k2 => $v2) {
									if (array_key_exists($v2, $v)) {
										$params_inf[$function_name][$k2] = $v[$v2];
									} else {
										$params_inf[$function_name][$k2] = $v2;
									}
								}
							}
							$rsl[$k][$function_name] = $fn($params_inf[$function_name], $info);
						} else if (is_array($param)) {
							foreach ($param as $k3 => $v3) {
								if ($params[$function_name][$k3]) {
									foreach ($params[$function_name][$k3] as $k2 => $v2) {
										if ($v2 == 'primary_fields') {
											$aaa = '';
											if ($primary_fields) {
												foreach ($primary_fields as $k4 => $v4) {
													if ($v4 != 1) {
														if ($v[$k4] != '') {
															$aaa .= str_replace('{items}', $v[$k4], $v4);
														}
													} else {
														$aaa .= $v[$k4].' ';
													}
												}
											}
											$params_inf[$k3.'_'.$function_name][$k2] = trim($aaa);
										} else if (array_key_exists($v2, $v)) {
											$params_inf[$k3.'_'.$function_name][$k2] = $v[$v2];
										} else {
											$params_inf[$k3.'_'.$function_name][$k2] = $v2;
										}
									}
								}
								$rsl[$k][$k3.'_'.$function_name] = $fn($params_inf[$k3.'_'.$function_name], $info);
							}
						}
					}
				} else {
					echo $fn;
				}
			}
			if ($fields_info) {
				$fields_inf = $fields;
				foreach ($rsl as $k => $v) {
					//set for file function
					$basics['id'] = $rsl[$k][$basics['table'].'__'.$basics['key']];
					foreach ($v as $k2 => $v2) {
						if (isset($fields_info[$k2])) {
							$field_name = $fields_info[$k2];
							$ftype = $fields_inf[$field_name]['type'];
							if ($ftype != 'E' && $ftype != '') {//check special function
								$fn = 'form_'.$ftype;
								//select, input, checkbox
								//TODO set for special type
								if ($ftype == 'file') {
									$fields_inf[$field_name]['default'][$field_name.'_updated'] = $rsl[$k][$k2.'_updated'];
									$fields_inf[$field_name]['default'][$field_name.'_updated_by'] = $rsl[$k][$k2.'_updated_by'];
									$fields_inf[$field_name]['default'][$field_name] = $v2;
								} else if ($ftype == 'city') {
									$fields_inf[$field_name]['default']['city'] = $v2;
								} else if ($ftype == 'money') {
									$fields_inf[$field_name]['default']['money'] = $v2;
								} else if ($ftype == 'autocomplete') {
									unset($fields_inf[$field_name]['default']);
									if ($fields_inf[$field_name]['save_name'] == 1) {
										$fields_inf[$field_name]['default']['id'] = $v2;
										$fields_inf[$field_name]['default']['name'] = $v2;
									} else {
										require_once PATH . 'modules/' . $fields_inf[$field_name]['entity'] . '.php';
										$fn_a = PREFIX . $fields_inf[$field_name]['entity'] . '_list';
										if ($fields_inf[$field_name]['list']) {
											$_REQUEST['type'] = $fields_inf[$field_name]['list'];
										}
										if (function_exists($fn_a) && $v2) {
											unset($_REQUEST['type']);
											$tmp = $fn_a($v2, $info);
											$tmp_id = array_keys($tmp);
											$id = $tmp_id[0];
											$fields_inf[$field_name]['default']['id'] = $id;
											$fields_inf[$field_name]['default']['name'] = $tmp[$id];
										}
									}
								} else {
									$fields_inf[$field_name]['default'] = $v2;
								}
								$fields_inf[$field_name]['displayonly'] = 1;
								$head = '';
								if (function_exists($fn)) {
									if ($short_detail[$k2]) {
										$head = '<strong>'.$fields_inf[$field_name]['head'].'</strong>: ';
									}
									if ($ftype == 'file') {
										$rsl[$k][$k2] = $head.$fn($field_name, $fields_inf[$field_name], $link, 'display', '', $basics);
									} else if ($ftype == 'autocomplete') {
										$fields_inf[$field_name]['listing'] = 1;
										$rsl[$k][$k2] = $head.$fn($k2, $fields_inf[$field_name]);
									} else {
										$rsl[$k][$k2] = $head.$fn($k2, $fields_inf[$field_name]);
									}
								} else {
									$rsl[$k][$k2] = $fn;
								}
							}
						}
					}
				}
			}
		}
	}
	
	//keep search history
	//we dont keep history when we do submit form [post_form]=1
	// && $_REQUEST['no_history'] != 1 && !$_REQUEST['link']
	if (!$_REQUEST['post_form'] && !$_REQUEST['id_panel'] && !$_REQUEST['opt']) {
		if (!$basics['entity_key']) {
			$basics['entity_key'] = $basics['entity'];
		}
	
		//add more options
		if ($_REQUEST['item_id'] && $basics['entity_key'] != $_REQUEST['mod'] && $_REQUEST['mod'] != 'settings') {
// 			$basics['entity_key'] .= '_' . $_REQUEST['mod'];
		}
/*
		//change search linked
		$search_linked = $entities[$entity]['search']['action_search_form'];
		if ($search_linked) {
			if ($cm_menu['M'][$basics['entity']]['M'] != '') {//for group menu
				$search_linked = str_replace('mod='.$entity, 'mod='.$cm_menu['M'][$basics['entity']]['M'].'&search_for='.$basics['entity_key'], $search_linked);
				//perhap we send view=search_result.. remove it!
				$search_linked = str_replace('&view=search_result', '', $search_linked);
				//process search use ajax all the time and we need to remove it!
				$search_linked = str_replace('ajax=1&', '', $search_linked);
			} else {//mod = other
				//beem added 2011-02-23 08:46
				if ($basics['mod_main']) {
					$search_linked = str_replace($basics['op'], $basics['mod_main'], $search_linked);
				}
		
				$search_linked = str_replace('ajax=1&', '', $search_linked);
				if (strstr($search_linked, 'entity=')) {
					$search_linked = str_replace('entity=' . $entity, '&search_for=' . $entity . '&entity=' . $entity, $search_linked);
				} else {
					$search_linked .= '&search_for=' . $entity . '&entity=' . $entity;
				}
			}
		
			//new rq 04 05 2011 keep search sql in search history
			$search_sql = $search['sql_search'];
	
			$sql = SQL('SELECT search_token
			FROM '.PREFIX.'fw_search_history
			WHERE search_entities=%s
			AND search_text=%s
			AND search_by=%d', $basics['entity_key'], $search['search_text'], $_SESSION[SESSION_L]);
			$search_history_token = $db->GetOne($sql, 'fw');
	
			if ($search_history_token && 1==2) {
				$param_qry = array(
					'table' => PREFIX . 'fw_search_history',
					'cols' => array(
						'search_link', '%s', $search_linked . $search['linked'] . $search['sort'],
						'search_date', '', 'NOW()',
						'search_text', '%s', $search['search_text'],
	
						//new rq 04 05 2011
						'search_sql', '%s', $search_sql,
						'search_num', '%d', $item_all
					),
					'where' => SQL('search_token=%s', $search_history_token),
				);
				db_query($param_qry, 1, 'fw');
			} else {*/
				$search_history_token = md5(time().$basics['entity_key'].$_SESSION[SESSION_L]);
				$keep = array($basics['entity_key'] => $_REQUEST[$basics['entity_key']]);
				$param_qry = array(
					'table' => PREFIX . 'fw_search_history',
					'cols' => array(
						'search_token', '%s', $search_history_token,
						'search_entities', '%s', $basics['entity_key'],

						'search_link', '%s', serialize($keep),
						'search_date', '', 'NOW()',
						'search_text', '%s', $search['search_text'],

						'search_by', '%d', $_SESSION[SESSION_L],
						'search_default', '%s', '0',

						//new rq 04 05 2011
						'search_sql', '%s', $search_sql,
						'search_num', '%d', $item_all
					),
				);
				db_query($param_qry, 1, 'fw');
			//}
		//}
	}
// 	echo '<pre>';
// 	print_r($rsl);
// 	echo '</pre>';
	//echo $sql_list . $sql_limit_page;
	return array('sql_list' => $sql_list . $sql_limit_page, 'item_all' => $item_all, 'data_values' => $rsl, 'pattern' => $pattern, 'search' => array('search_token' => $search_token, 'search_id' => $search_id, 'search_checksum' => $item_all, 'search_history_token' => $search_history_token));
}

//check role permission
function gain_check_permission($act, $entity, $v){
	global $cm_menu;
	
	$entity_info = gain_entity_get_entity_detail($entity);
	$entity_check = $entity_info['mod_main'];

	$pass = 0;
	if ($cm_menu['M'][$entity_check]['P'] == 1) {
		if ($v['gain_entity_permission__p_'.$act] == 1 || $_SESSION[SESSION_P]['permissions']['menu'][$entity_check]['permission'] == 1) {
			$pass = 1;
		}
	} else {
		$pass = 1;
	}
	
	return $pass;
}

/**
 *
 * @param $param
 * @param $inf
 * @return unknown_type
 */
function gain_edit($param, $inf) {
	$basics = $inf['basics'];
	$fields = $inf['fields'];
	$v = $inf['row'];
	$item_id = $v[$basics['table'].'__'.$basics['key']];

	$pass = gain_check_permission('modify', $basics['entity'], $v);
	if (check_permission('modify', $basics['entity'], '', $item_id, $inf['item_id_all']) && $pass == 1) {
		$fn = 'gain_list_edit_check';
		if (function_exists($fn)) {
			$ok = $fn($v);
		} else {
			$ok = 1;
		}
		if ($ok == 1) {
			// set new linked.. check function
			$fn = 'gain_linked_edit_set';
			if (function_exists($fn)) {
				$linked = $fn($item_id, $v, $basics);
			}

			if ($linked == '') {
				$linked = 'index.php?mod=' . $basics['op'] . '&link=edit&id='.$item_id;//TODO.$basics['linked']
			}
			return '<a href="'.$linked.'"><img src="im/edit.png" title="'.msg('edit').'" /></a>';
		}
	}
}

/**
 *
 * @param $param
 * @param $inf
 * @return unknown_type
 */
function gain_edit_popup($param, $inf){
	$basics = $inf['basics'];
	$fields = $inf['fields'];
	$v = $inf['row'];
	$item_id = $v[$basics['table'].'__'.$basics['key']];
	
	$pass = gain_check_permission('modify', $basics['entity'], $v);
	if (check_permission('modify', $basics['entity'], '', $item_id, $inf['item_id_all']) && $pass == 1) {
		$fn = 'gain_list_edit_check';
		if (function_exists($fn)){
			$ok = $fn($v);
		} else {
			$ok = 1;
		}

		if ($ok == 1) {//TODO $basics['linked'].
			return '<a href="#'.msg('fw_edit').$item_id.'" onclick="show_popup_in_search(this,\''.$basics['op'].'\',\''.$item_id.'\',\'edit\',0);"><img src="im/edit.png" title="'.msg('edit').'" /></a>';
		}
	}
}

/**
 *
 * @param $param
 * @param $inf
 * @return unknown_type
 */
function gain_duplicate($param, $inf){
	$basics = $inf['basics'];
	$fields = $inf['fields'];
	$v = $inf['row'];
	if (check_permission('add', $basics['entity'])) {
		$fn = 'gain_list_edit_check';
		if (function_exists($fn)){
			$ok = $fn($v);
		} else {
			$ok = 1;
		}
		$item_id = $v[$basics['table'].'__'.$basics['key']];
		if ($ok == 1) {
			return '<a href="index.php?mod='.$basics['op'].'&link=edit&id='.$item_id.'&opt=11"><img src="im/duplicate.png" title="'.msg('duplicate').'" /></a>';
		}
	}
}

/**
 *
 * @param $param
 * @param $inf
 * @return unknown_type
 */
function gain_duplicate_popup($param, $inf){
	$basics = $inf['basics'];
	$fields = $inf['fields'];
	$v = $inf['row'];
	if (check_permission('add', $basics['entity'])) {
		$fn = 'gain_list_edit_check';
		if (function_exists($fn)){
			$ok = $fn($v);
		} else {
			$ok = 1;
		}
		$item_id = $v[$basics['table'].'__'.$basics['key']];
		if ($ok == 1) {
			return '<a href="#'.msg('fw_edit').$item_id.'" onclick="show_popup_in_search(this,\''.$basics['op'].'&opt=11\',\''.$item_id.'\',\'edit\',0);"><img src="im/duplicate.png" title="'.msg('duplicate').'" /></a>';
		}
	}
}

/**
 *
 * @param $param
 * @param $inf
 * @return unknown_type
 */
function gain_delete($param, $inf){
	$basics = $inf['basics'];
	$fields = $inf['fields'];
	$v = $inf['row'];
	$item_id = $v[$basics['table'].'__'.$basics['key']];

	$pass = gain_check_permission('delete', $basics['entity'], $v);
	if (check_permission('delete', $basics['entity'], '', $item_id, $inf['item_id_all']) && $pass == 1) {
		$fn = 'gain_list_delete_check';
		if (function_exists($fn)) {
			$ok = $fn($basics['entity'], $v);
		} else {
			$ok = 1;
		}
		if ($basics['refresh_action_ajax']) {
			$refresh = '#'.$basics['refresh_action_ajax'];
		} else {
			$refresh = '#'.$basics['entity'].'_search_result';
		}
		if ($basics['remove_entity_name']) {
			$remove_entity_name = $basics['remove_entity_name'];
		} else {
			$remove_entity_name = msg($basics['entity']);
		}
		if ($ok == 1) {
			return '<a href="#' . msg('fw_delete') . $item_id . '" onclick="confirmation(\'' . msg('confirm_for_delete_item') . ' ' . $remove_entity_name . '?\',\'index.php?ajax=1&mod=' . $basics['op'] . '&id=' . $item_id . '&opt=4\',\'' . $refresh . '\')"><img src="im/remove.png" title="' . msg('fw_delete') . '" /></a>';
		}
	}
}
/**
 * options FAV
 * @param $fields
 * @param $basics
 * @param $v
 * @return unknown_type
 */
function gain_show_fav($param, $inf){
	$basics = $inf['basics'];
	$fields = $inf['fields'];
	$row = $inf['row'];
	//get primary fields .. return fiels>>primary fields was set
	$param_fields = fw_check_param_field($fields, 'primary_field');
	//check info
	if ($param_fields['primary_field']) {
		foreach ($param_fields['primary_field'] as $k => $v2) {
			$item_name .= $row['field_'.$v2].' ';
		}
	}
	$id_item = $row[$basics['table'].'__'.$basics['key']];
	$entity = $basics['entity'];

	$link = gain_entity_get_entity_detail($basics['entity'], 'detail_link');
	if ($link == '') {
		$link = 'index.php?mod=' . $basics['op'] . '&link=detail&id=';
	}
	$link .= $id_item;

	return fav_icon($entity, $id_item, trim($item_name), $link);
}

/**
 * show search history, need to modify it for this project .. i dont check it yet
 * @param $entity
 * @return unknown_type
 */
function gain_search_history(){
	global $db;
	if ($_REQUEST['search_token'] || $_REQUEST['set_mod']) {
		if ($_REQUEST['search_entity']) {
			$sql = SQL('UPDATE '.PREFIX.'fw_search_history 
			SET search_default=0 
			WHERE search_by=%d
			AND search_entities=%s', $_SESSION[SESSION_L], $_REQUEST['search_entity']);
			$db->Execute($sql, 'fw');
		} else {
			$sql = SQL('UPDATE '.PREFIX.'fw_search_history 
			SET search_default=0 
			WHERE search_token=%s', $_REQUEST['search_token']);
			$db->Execute($sql, 'fw');
		}
		
		if ($_REQUEST['search_default'] != 1) {
			if ($_REQUEST['search_token'] == '') {
				//set search_default to last search token
				$sql = SQL('SELECT search_token 
				FROM '.PREFIX.'fw_search_history 
				WHERE search_by=%d 
				AND search_entities=%s 
				ORDER BY search_date DESC', $_SESSION[SESSION_L], $_REQUEST['search_entity']);
				$_REQUEST['search_token'] = $db->GetOne($sql);
			}
			
			$sql = SQL('UPDATE '.PREFIX.'fw_search_history SET search_default=1 
			WHERE search_by=%d 
			AND search_token=%s', $_SESSION[SESSION_L], $_REQUEST['search_token']);
			$db->Execute($sql, 'fw');
		}
		exit;
	}
	$entity = $_REQUEST['entity'];
	$sql = SQL('SELECT search_token, search_text, search_link, search_by, search_date, search_default
	FROM '.PREFIX.'fw_search_history
	WHERE search_by=%d
	AND search_entities=%s
	ORDER BY search_date DESC
	LIMIT 0,10', $_SESSION[SESSION_L], $entity);
	$rsl = clean($db->GetAssoc($sql, 'fw'));

	$r .= '<div class="popupHeader">'.msg('search history').'</div><div class="detailsInfo">';
	if ($rsl) {
		$t .= '<table cellpaddin="4" cellspacing="1" width="100%">';
		$ck = 0;
		$search_default_show = 0;
		foreach ($rsl as $search_token => $v) {
			if ($v['search_text']) {
				//refresh page
				if (strlen($v['search_text'])>53) {
					$show_text = substr($v['search_text'], 0, 53).'..';
				} else {
					$show_text = $v['search_text'];
				}

				if ($v['search_default'] == 1) {
					$search_default = '<img src="im/bookmark_active.png" title="'.msg('fw_bookmark_active').'"/>';
					$search_default_show = 1;
				} else {
					$search_default = '<img src="im/bookmark.png" title="'.msg('fw_bookmark').'"/>';
				}
				//set new link
				if ($v['search_link']) {
					$s = explode('entity=', $v['search_link']);
					$search_linked = $s[0];
				}

				$t .= '<tr><td><a href="#default" class="set_search_default" onclick="set_search_default(this,\''.$search_token.'\');" rel="'.$v['search_default'].'">'.$search_default.'</a> <a href="'.$search_linked.'&show_search='.$search_token.'">'.$show_text.'</a><hr style="height: 1px;"/></td></tr>';
				++$ck;
			}
		}

		if ($search_default_show == 0) {
			$sql = SQL('SELECT search_token, search_text, search_link, search_by, search_date, search_default
			FROM '.PREFIX.'fw_search_history
			WHERE search_default=1
			AND search_by=%d
			AND search_entities=%s
			ORDER BY search_date DESC', $_SESSION[SESSION_L], $entity);
			$val = clean($db->GetRow($sql, 'fw'));
			if ($val) {
				if (strlen($val['search_text'])>53) {
					$show_text = substr($val['search_text'], 0, 53).'..';
				} else {
					$show_text = $val['search_text'];
				}

				//set new link
				if ($val['search_link']) {
					$s = explode('entity=', $val['search_link']);
					$search_linked = $s[0];
				}

				$search_default = '<img src="im/bookmark_active.png" title="'.msg('fw_bookmark_active').'"/>';
				$t .= '<tr><td><a href="#default" class="set_search_default" onclick="set_search_default(this,\''.$val['search_token'].'\');" rel="'.$val['search_default'].'">'.$search_default.'</a> <a href="'.$search_linked.'&show_search=1&search_for='.$entity.'">'.$show_text.'</a><hr style="height: 1px;"/></td></tr>';
			}
		}
		$t .= '</table>';
	}
	if ($ck == 0 || !$rsl) {
		$t = msg('!history');
	}
	$r .= $t.'</div>';
	return $r;
}

function gain_search_default_get($basics) {
	global $db;

	$sql = SQL('SELECT search_link
	FROM '.PREFIX.'fw_search_history
	WHERE search_entities=%s
	AND search_by=%d
	AND search_default=1', $basics['entity_key'], $_SESSION[SESSION_L]);
	$search_link = $db->GetOne($sql, 'fw');

	if ($search_link) {

// 		$a = explode('&entity=' . $basics['entity_key'], $search_link);
// 		parse_str($a[1], $parsed);

		$parsed = unserialize($search_link);

		unset($parsed[$basics['entity_key']]['adv']);
		unset($parsed[$basics['entity_key']]['page']);
		unset($parsed[$basics['entity_key']]['sort_by']);
		unset($parsed[$basics['entity_key']]['sort_order']);
		$_REQUEST['default_search'] = $parsed;
	}
}

/**
 * for redirect to last search for each module
 *
 * @param $entity
 * @return unknown_type
 */
function gain_search_history_get($basics){
	global $db, $cm_menu;
	$entity_arr[] = $basics['entity_key'];
	if (!$entity_arr) {
		return;
	}
	//unset($_REQUEST);
	//$_REQUEST['history'] = 1;
	foreach ($entity_arr as $k => $entity) {
		//add more options
		if ($_REQUEST['item_id'] && $entity != $_REQUEST['mod'] && $cm_menu['M'][$entity]['M'] != $_REQUEST['mod'] && $_REQUEST['mod'] != 'settings') {
			$entity .= '_' . $_REQUEST['mod'];
		}

		if ($entity != '') {
			if ($_REQUEST['show_search'] != '') {
				$sql = SQL('SELECT search_link
				FROM '.PREFIX.'fw_search_history
				WHERE search_token=%s', $_REQUEST['show_search']);
				$search_link = $db->GetOne($sql, 'fw');
			} else {
				//20110524 always display last search
				$sql = SQL('SELECT search_text, search_link, search_default
				FROM '.PREFIX.'fw_search_history
				WHERE search_entities=%s
				AND search_by=%d
				ORDER BY search_date DESC
				LIMIT 1', $entity, $_SESSION[SESSION_L]);
				$linked_info = $db->GetRow($sql, 'fw');

				if ($linked_info) {
					$search_link = $linked_info['search_link'];
				}
			
				if ($linked_info['search_default'] == 0) {
					if ($_REQUEST['clear'] == msg('fw-default') || !$linked_info) {
						//get fav search first
						$sql = SQL('SELECT search_link
						FROM '.PREFIX.'fw_search_history
						WHERE search_entities=%s
						AND search_by=%d
						AND search_default=1', $entity, $_SESSION[SESSION_L]);
						$search_link = $db->GetOne($sql, 'fw');
						$default_search = 1;
					}
				}
			}

			if ($search_link != '') {
// 				$a = explode('&entity=' . $basics['entity_key'], $search_link);//TODo beem change this action
				$parsed = unserialize($search_link);
				unset($parsed['ajax']);
// 				echo '<pre>';
// 				print_r($parsed);
// 				echo '</pre>';
				//if we get search parse search params and merge with REQUEST array
				if ($parsed) {
					if ($_REQUEST['item_id']) {
						$item_id = $_REQUEST['item_id'];
					}
//					parse_str($a[1], $parsed);
					if ($default_search == 1) {
						unset($parsed['adv']);
						//unset($parsed['page']);
					}
					$_REQUEST = array_merge($_REQUEST, $parsed);
					if ($item_id) {
						$_REQUEST['item_id'] = $item_id;
					}
					//if ($_REQUEST['item_id']) {
						unset($_REQUEST[$basics['entity_key']]['adv']);
//						unset($_REQUEST[$basics['entity_key']]['limit']);
//						unset($_REQUEST[$basics['entity_key']]['page']);
//						unset($_REQUEST[$basics['entity_key']]['sort_by']);
//						unset($_REQUEST[$basics['entity_key']]['sort_order']);
					//}
				}
			}
		}
	}
}

/**
 * fw_search_input('beem',array('inf' => $inf, 'field' => $field, 'main_table' => $basics['table']));
 * @param $keyword
 * @param $param
 * @return unknown_type
 */
function fw_search_input($keyword, $param){
	$inf = $param['inf'];
	$field = $param['field'];
	$table = $param['main_table'];

	if ($keyword{0}.$keyword{1} == '*?' || $keyword{0}.$keyword{1} == '?*') {
		$op = '%';
		$keyword = substr($keyword, 2);
		$sep = 1;
	} else if ($keyword{0} == '*') {
		$op = '%';
		$keyword = substr($keyword, 1);
	} else if ($keyword{0} == '?') {
		$sep = 1;
		$keyword = substr($keyword, 1);
	}

	if (strstr($keyword, ' ') && $sep == 1) {
		$word_search = explode(' ', $keyword);
	} else {
		$word_search[] = $keyword;
	}

	$sql_search = ' (';
	foreach ($word_search as $k4 => $v4) {
		++$cnt;
		$v4 = mysql_real_escape_string($v4);
		if ($cnt > 1) {
			$sql_search .= ' OR ';
		}

		if ($inf['lookup']) {
			$sql_search .= $inf['lookup']['table'].'.'.$field.' LIKE "'.$op.$v4.'%"';
		} else if (strstr($field, '.')) {
			$sql_search .= $field.' LIKE "'.$op.$v4.'%"';
		} else {
			if ($table) {
				$fieldx = $table.'.'.$field;
			} else {
				$fieldx = $field;
			}
			$sql_search .= $fieldx.' LIKE "'.$op.$v4.'%"';
		}
	}
	$sql_search .= ')';

	return $sql_search;
}

/**
 * For tabs need to define array search-quick
 * example:
 * $search['quick'] = array(
		'default' => array(
			'outcome' => '1', // select
			'archive' => 'N', // select
			'id_department' => array(1, 2) //checkbox
		),
		'form_config' => array(
			'field_type' => array(
				'id_client' => 'select'
			),
			'form_id' => ''
		)
	);
 * //select, input, checkbox
 * @param $entity
 * @param $entities
 */
function fw_search_quick($entity, $entities){
	$search = $entities['search'];
	$search_fields = $entities['search']['search_fields'];
	$fields = $entities['fields'];
	$basics = $entities['basics'];

	$cleanVar = fw_data_cleanup($fields, $basics);
	$fields  = $cleanVar[0];
	$basics  = $cleanVar[1];

	if ($search_fields) {
		foreach ($search_fields as $k => $v) {
			if ($search['quick']['form_config']['fields_type'][$k]) {
				$search_fields[$k]['type'] = $search['quick']['form_config']['fields_type'][$k];
			} else if ($fields[$k]) {
				if (!$search_fields[$k]['type']) {
					//change fields type
					if ($fields[$k]['type'] == 'radio') {
						$fields[$k]['type'] = 'select';
					}

					//set fileds type
					if ($fields[$k]['type'] == '') {
						$search_fields[$k]['type'] = 'input';
					} else {
						$search_fields[$k]['type'] = $fields[$k]['type'];
					}
				}
			}
		}
	}

	//overwrite type
	$r = '<span id="'.$entity.'_quick">';
	if ($search['quick']) {
		if ($search['quick']['form_config']['entity_key']) {
			$entity_key = $search['quick']['form_config']['entity_key'];
		} else {
			$entity_key = $entity;
		}
		//beem add 2011-01-31
		if ($basics['refresh_action_ajax']) {
			$entity_key = $basics['refresh_action_ajax'];
		}
		$class = '';
		if ($_REQUEST['button_name'] == $entity.'_all') {
			$class = ' class="ui-state-focus"';
		}
		$r .= '<button onclick="fw_search_quick(\''.$entity.'\', \'clear\', \''.$entity_key.'\',\'all\');"'.$class.'>all</button>';
		foreach ($search['quick'] as $button_name => $field_search) {
			if ($button_name != 'form_config') {
				$class = '';
				$button_name_check = str_replace(' ', '_', $button_name);
				if ($_REQUEST['button_name'] == $basics['entity'].'_'.$button_name_check) {
					$class = ' class="ui-state-focus"';
				}
				$r .= '<button'.$class;
				$param = '';
				if ($field_search) {
					foreach ($field_search as $field_name => $default) {
						//separate type||field_name||value;;
						if ($search_fields[$field_name]['type'] == 'checkbox') {
							if (is_array($default)) {
								$param .= $search_fields[$field_name]['type'].'||'.$field_name.'||'.implode(';', $default).';;';
							}
						} else {
							$param .= $search_fields[$field_name]['type'].'||'.$field_name.'||'.$default.';;';
						}
					}
				}
				$r .= ' onclick="fw_search_quick(\''.$entity.'\', \''.$param.'\', \''.$entity_key.'\', \''.$button_name_check.'\');">'.msg('bt_'.$basics['entity'].'_'.$button_name);
				$r .= '</button>';
			}
		}
	}
	$r .= '<button>advanced search</button>';
	$r .= '</span>';

	return $r . '
	<script type="text/javascript">
		$(document).ready(function(){
			$("#'.$entity.'_quick button:last")
			.button({
				icons: {
					primary: "ui-icon-search",
				}
			})
			.click(function() {
				show_search_form_js(\''.$entity.'\');
				return false;
			})
			.parent().buttonset();
		});
	</script>';
}

function fw_cache_items_get($search_token){
	global $db;
	$sql = SQL('SELECT search_id FROM gain_fw_search_cache WHERE search_token=%s', $search_token);
	$sql_search_id = $db->GetOne($sql);
	if ($sql_search_id) {
		$db->Execute('SET SESSION group_concat_max_len = 1000000');
		return $db->GetOne($sql_search_id);
	} 
}
?>